package com.mars.ms.threadpool;

import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * author by: mars
 * Date: 2022/3/19 23:23
 * Description: spring 的线程池调度执行器
 */
public class SpringThreadPoolTaskScheduleDemo {

    public static void main(String[] args) {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        scheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        scheduler.initialize();

        List<MssTask> taskList = new ArrayList<>();
        taskList.add( new MssTask(new Runnable() {
            @Override
            public void run() {
                System.out.println(new Date() + ",任务1");
            }
        }, "0/1 * * * * ?"));

        taskList.add( new MssTask(new Runnable() {
            @Override
            public void run() {
                System.out.println(new Date() + ",任务2");
            }
        }, "0/5 * * * * ?"));

        for (MssTask mssTask : taskList) {
            scheduler.schedule(mssTask.getRunnable(), new CronTrigger(mssTask.getCron()));
        }

    }
}

class MssTask {
    Runnable runnable;
    String cron;

    public MssTask(Runnable runnable, String cron) {
        this.runnable = runnable;
        this.cron = cron;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public void setRunnable(Runnable runnable) {
        this.runnable = runnable;
    }

    public String getCron() {
        return cron;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }
}



